import "./OpArticlesPage.scss";
import React, {createRef} from "react";
import {ReactComponentPage} from "../../class/ReactComponentPage";
import {Button, message} from "antd";
import {Link, RouteComponentProps} from "react-router-dom";
import {TableBookList} from "../../../common/class/TableBookList";
import tableBookList from "../../../common/function/tableBookList";
import {BookInfo} from "../../components/BookInfo/BookInfo";
import {ArticleAddPop} from "../../components/ArticleAddPop/ArticleAddPop";
import {TableArticleList} from "../../../common/class/TableArticleList";
import {mixedObj} from "../../../common/function/objFunc";
import {ArticlesTable} from "../../components/ArticlesTable/ArticlesTable";
import {BookUpdater} from "../../../common/class/BookUpdater";

const tableArticleList = new TableArticleList();

export namespace OpArticlesPage {

    export interface LocationParams {
        bookId: string;
    }
    export interface Props extends ReactComponentPage.Props, RouteComponentProps<LocationParams> {
    }
    export interface State extends ReactComponentPage.State {
        bookId: number;
        bookData: Partial<TableBookList.Data>;
        showPop: boolean;
        articleData: Partial<TableArticleList.Data>;
    }
}

export class OpArticlesPage extends ReactComponentPage<OpArticlesPage.Props, OpArticlesPage.State> {
    public readonly state = {
        bookId: 0,
        bookData: {
            name: "",
        },
        showPop: false,
        articleData: {},
    };
    protected refTable = createRef<ArticlesTable>();
    public render() {
        return (<div className={this.getClsName("op-articles-page-component")}>
            <h3 className="page-title">章节列表页面</h3>
            <div className="row first-row">
                <Button type="primary">
                    <Link to="/operate/books">返回书籍列表</Link>
                </Button>
            </div>
            <BookInfo baseData={this.state.bookData} className="row">
                <div className="info-row">
                    <Button type="primary" onClick={this.onClickAdd.bind(this)}>添加章节</Button>
                    <Button type="danger" onClick={this.onClickDel.bind(this)}>删除章节</Button>
                    <Button type="default" onClick={this.onClickSync.bind(this)}>同步信息</Button>
                </div>
            </BookInfo>
            <ArticlesTable
                ref={this.refTable}
                bookId={this.state.bookId}
                onEditItem={this.editArticle.bind(this)}
            />
            <ArticleAddPop
                formData={this.state.articleData}
                showPop={this.state.showPop}
                onCloseModal={this.onCloseModal.bind(this)}
            ></ArticleAddPop>
        </div>);
    }
    public componentDidMount(): void {
        this.resetBookData();
    }
    protected editArticle(articleData: TableArticleList.Data) {
        this.setState({
            showPop: true,
            articleData,
        });
    }
    protected resetBookData() {
        const bookId = parseInt(this.props.match.params.bookId) || 0;
        if (bookId) {
            this.setBookDataFromDB(bookId);
        } else {
            message.error(`不可能的书籍标志: ${bookId}`);
        }
    }
    protected setBookDataFromDB(bookId: number) {
        tableBookList.select().where({
            id: bookId,
        }).find().then((row) => {
            this.setState({
                bookId,
                bookData: row,
            });
        }).catch((err) => {
            console.error(err);
            message.error(`错误的书籍标志: ${bookId}`);
        });
    }
    protected onClickAdd() {
        this.setState({
            showPop: true,
            articleData: {},
        });
    }
    protected refreshList() {
        this.refTable.current.refreshList();
    }
    protected onCloseModal(state: ArticleAddPop.ModalCloseState, values: Partial<TableArticleList.Data>) {
        if (state === "cancel") {
            this.setState({
                showPop: false,
            });
        } else if (state === "okay") {
            this.updateValues(values);
        }
    }
    protected updateValues(values: Partial<TableArticleList.Data>) {
        const bookId = this.state.bookId;
        const articleData = this.state.articleData as Partial<TableArticleList.Data>;
        if (articleData && articleData.id) {
            values.id = articleData.id;
        }
        tableArticleList.saveData(mixedObj({
            book_id: bookId,
        }, values)).then(() => {
            message.success("更新成功");
            this.refreshList();
            this.setState({
                showPop: false,
            });
        }).catch((err) => {
            message.error("更新失败");
            console.error(err);
        });
    }
    protected onClickDel() {
        const table = this.refTable.current;
        table.delByIdList(table.getSelectedIdList());
    }
    protected onClickSync() {
        const bookUpdater = new BookUpdater();
        const table = this.refTable.current;
        const bookId = this.state.bookId;
        table.showLoading();
        bookUpdater
            .updateById(bookId)
            .then((res) => {
                if (res && res.updated) {
                    this.afterSyncArticleList(bookId, res);
                } else {
                    this.refTable.current.refreshList();
                }
                message.success("同步完成");
            })
            .catch((err) => {
                message.error("同步出错");
                console.error(err);
                this.refTable.current.refreshList();
            });
    }
    protected afterSyncArticleList(bookId: number, result: BookUpdater.UpdateResult) {
        tableBookList
            .sqlSet({
                last_update_time: result.updateTime,
                update_frequency: result.updateFrequency,
            })
            .where("id", bookId)
            .update()
            .catch((err) => {
                message.error("更新书籍信息出错");
                console.error(err);
            })
            .finally(() => {
                this.refTable.current.refreshList();
            });
    }
}
